package cn.itcast.system.web.action;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.web.action.BaseAction;
import cn.itcast.system.service.UserService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	
	@Autowired
	private UserService userService;
	
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	
	
	@Action(value = "user_login", results = { @Result(name = "success", location = "index.html", type = "redirect"),
			@Result(name = "login", location = "login.html", type = "redirect") })
	public String login() {
		Subject subject = SecurityUtils.getSubject();

		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
		
		try {
			subject.login(token);
			//登入成功
			return SUCCESS;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			//登入失败
			return LOGIN;
		}
	}
	//注销
	@Action(value="login_out",results={@Result(name="success",location="/login.html",type="redirect")})
	public String loginOut(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}
	
	//
	@Action(value="user_list",results={@Result(name="success",type="json")})
	public String findUser(){
		List<User> userData = userService.findAll();
		ActionContext.getContext().getValueStack().push(userData);
		return SUCCESS;
	}
	
	@Action(value="user_save",results={@Result(name="success",location="pages/system/userlist.html",type="redirect")})
	public String saveUser(){
		userService.save(model,roleIds);
		return SUCCESS;
	}
}
